package com.su.dolphin.utils;

import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.drawable.StateListDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.su.dolphin.DpApp;

public class ViewUtil
{
    public static View inflateView(int resource, ViewGroup root, boolean attachToRoot) {
        View view = LayoutInflater.from(root.getContext()).inflate(resource, root, attachToRoot);
        return view;
    }
    
    public static View inflateView(int resource, ViewGroup root) {
        //View view = LayoutInflater.from(parent.getContext()).inflate(redId, parent, false);
        return inflateView(resource, root, false);
    }
    
    /**
     * 通过制定的 layout xml 生成一个view
     * 
     * @param redId
     *            layout的id
     * @param context
     * @return
     */
    public static View inflateView(int redId, Context context) {
        View view = LayoutInflater.from(context).inflate(redId, null, false);
        return view;
    }
    
    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(float dpValue) {
        final float scale = DpApp.getContext().getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
    
    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(float pxValue) {
        final float scale = DpApp.getContext().getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
    
    public static ColorStateList createColorStateList(int normal, int pressed) {
        ColorStateList myColorStateList = new ColorStateList(new int[][] { new int[] { android.R.attr.state_pressed }, new int[] { android.R.attr.state_focused }, new int[] { android.R.attr.state_checked }, new int[] { -android.R.attr.state_enabled }, new int[] { android.R.attr.state_enabled } //state
        }, new int[] { pressed, pressed, pressed, normal, normal });
        return myColorStateList;
    }
    
    public static StateListDrawable createStateListDrawable(int normal, int pressed) {
        Resources resources = DpApp.getContext().getResources();
        StateListDrawable mStateListDrawable = new StateListDrawable();
        mStateListDrawable.addState(new int[] { android.R.attr.state_pressed }, resources.getDrawable(pressed));
        mStateListDrawable.addState(new int[] { android.R.attr.state_focused }, resources.getDrawable(pressed));
        mStateListDrawable.addState(new int[] { android.R.attr.state_checked }, resources.getDrawable(pressed));
        mStateListDrawable.addState(new int[] { -android.R.attr.state_enabled }, resources.getDrawable(pressed));
        mStateListDrawable.addState(new int[] { android.R.attr.state_enabled }, resources.getDrawable(normal));
        return mStateListDrawable;
    }
}
